package es.esi.gemde.methodmanager.service.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;

import es.esi.gemde.methodmanager.CommandConstants;
import es.esi.gemde.methodmanager.MethodManagerPlugin;

public class SelectFolderCommandHandler extends AbstractHandler {
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String onlyWorkspace = event.getParameter(CommandConstants.ONLYWORKSPACE_PARAM_ID);
		
		if (Boolean.parseBoolean(onlyWorkspace)) {
			ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(new Shell(), new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider());
			dialog.addFilter(new ViewerFilter() {
				
				@Override
				public boolean select(Viewer viewer, Object parentElement, Object element) {
					return element instanceof IContainer;
				}
			});
			dialog.setValidator(new ISelectionStatusValidator() {
				
				@Override
				public IStatus validate(Object[] selection) {
					if (selection.length != 1) {
						return new Status(IStatus.ERROR, MethodManagerPlugin.PLUGIN_ID, "Select only one folder");
					}
					return new Status(IStatus.OK, MethodManagerPlugin.PLUGIN_ID, "");
				}
			});
			dialog.setTitle("Select a folder");
			dialog.setMessage("Select a folder in the workspace");
			dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
			if (dialog.open() == Dialog.OK) {
				return ((IContainer) dialog.getFirstResult()).getLocation().toOSString();
			}
		}
		else {
			DirectoryDialog dialog = new DirectoryDialog(new Shell());
			dialog.setMessage("Select any folder in the system");
			return dialog.open();
		}
		
		return null;
	}

}
